import React from 'react';
import { Form, Input, Button, Radio, message, Checkbox } from 'antd';
import * as routerActions from 'react-router-redux';
import Api from 'Utils/api';
import { connect } from 'react-redux';
import { chaeckMobilePhone } from 'Utils/index';
import MessageType from 'Constants/MessageType';
import { BROWSER_MODE } from 'Constants/webConstants';
import { RESOURCE_HOST, CAPTCHA_SECONDS } from '../../../../constants/config';
import OnVideoModal from '../Modal/OnVideoModal';
import OnAudioModal from '../Modal/OnAudioModal';
import FlagTitle from '../../FlagTitle';
import './advice.scss';
import SubmitModal from '../Modal/SubmitReport';

const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const { TextArea } = Input;
let canSendCaptcha = true;
const CaptchaSeconds = CAPTCHA_SECONDS;
class AdviceDetails extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      audioSrc: '',
      videoSrc: '',
      radioValue: true,
      remainingSecond: CaptchaSeconds,
      loading: false,
      anonymous: false,
    };
    this.handSubmit = ::this.handSubmit;
    this.handCliCk = ::this.handCliCk;
    this.onVideoClick = ::this.onVideoClick;
    this.validation = ::this.validation;
    this.onAudioClick = ::this.onAudioClick;
    this.OnVideoEditOk = ::this.OnVideoEditOk;
    this.OnAudioEditOk = ::this.OnAudioEditOk;
    this.onChangeRadio = ::this.onChangeRadio;
    this.sendCaptcha = ::this.sendCaptcha;
    this.countDownSeconds = ::this.countDownSeconds;
    this.returnReportType = ::this.returnReportType;
    this.changeAnonymous = ::this.changeAnonymous;
  }
  componentWillUnmount() {
    clearInterval(this.timer);
  }
  changeAnonymous(e) {
    this.setState({
      anonymous: e.target.checked,
    });
  }
  handCliCk() {
    this.props.dispatch(routerActions.goBack());
  }

  onVideoClick() {
    this.OnVideoModal.showModal();
  }
  onAudioClick() {
    this.OnAudioModal.showModal();
  }
  validation(value) {
    if (!value.title || !value.content || !value.suggester || !value.id_no || !value.phone || !value.code) {
      return false;
    }
    return true;
  }
  handSubmit() {
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const formValue = this.props.form.getFieldsValue();
        const { videoSrc, audioSrc, anonymous } = this.state;
        if (!this.validation(formValue)) {
          message.info('请完善信息', 3);
          return;
        }
        // 检查手机号格式
        if (!chaeckMobilePhone(formValue.phone)) {
          message.info('联系电话格式错误', 3);
          return;
        }
        this.setState({ loading: true });
        const data = {
          ...formValue,
          media_type: this.returnReportType(),
          is_anonymity: anonymous,
        };
        if (this.state.radioValue && videoSrc) {
          data.type = videoSrc;
        }
        if (!this.state.radioValue && audioSrc) {
          data.type = audioSrc;
        }
        const sumApi = new Api({
          method: 'POST',
          path: '/suggests/user',
          data,
          success: () => {
            this.setState({ loading: false });
            this.submitModal.showModal();
            setTimeout(() => {
              this.handCliCk();
            }, 15000);
          },
          error: (msg) => {
            message.error(msg);
            this.setState({ loading: false });
          }
        });
        sumApi.run();
      }
    });
  }
  returnReportType() {
    const { videoSrc, audioSrc } = this.state;
    if (this.state.radioValue && videoSrc) {
      return MessageType.VIDEO;
    }
    if (!this.state.radioValue && audioSrc) {
      return MessageType.AUDIO;
    }
    return '';
  }
  OnVideoEditOk(id) {
    document.getElementById('videoForm').innerHTML = `<video controls preload class="video-content">
                                                       <source src=${RESOURCE_HOST}${id} type="video/mp4">
                                                    </video>`;
    this.setState({
      videoSrc: id
    });
  }
  OnAudioEditOk(id) {
    document.getElementById('audioForm').innerHTML = `<audio controls class="audio-content">
                                                    <source src=${RESOURCE_HOST}${id} type="audio/mp3">
                                                    </audio>`;
    this.setState({
      audioSrc: id
    });
  }
  onChangeRadio(e) {
    this.setState({
      radioValue: e.target.value
    });
  }
  // 发送验证码
  sendCaptcha() {
    const phone = this.props.form.getFieldsValue().phone;
    if (!canSendCaptcha) {
      return;
    }

    if (!phone) {
      message.warning('请先输入手机号', 3);
      return;
    }
    // 检查手机号格式
    if (!chaeckMobilePhone(phone)) {
      message.info('联系电话格式错误', 3);
      return;
    }
    canSendCaptcha = false;
    setTimeout(() => {
      this.setState({
        remainingSecond: CaptchaSeconds,
      }, () => {
        this.countDownSeconds();
      });
    }, 0);

    const api = new Api({
      method: 'POST',
      path: '/phone/verify_code',
      data: {
        phone,
        response: 'tmind'
      },
      error: () => {
        this.setState({
          remainingSecond: 0,
        }, () => {
          canSendCaptcha = true;
          clearInterval(this.timer);
          this.timer = undefined;
        });
      },
    });
    api.run();
  }
  /**
   * 验证码倒计时
   */
  countDownSeconds() {
    const remainingSecond = this.state.remainingSecond - 1;
    if (remainingSecond < 0) {
      canSendCaptcha = true;
      clearInterval(this.timer);
      this.timer = undefined;
    } else {
      if (!this.timer) {
        this.timer = setInterval(this.countDownSeconds, 1000);
      }
      this.setState(preState => (Object.assign({}, preState, {
        remainingSecond,
      })));
    }
  }
  render() {
    const { form, initialValue, mode } = this.props;
    const { getFieldDecorator } = form;
    const { radioValue, audioSrc, remainingSecond } = this.state;
    const isVertical = BROWSER_MODE.isVertical(mode);
    return (
      <div className={`${isVertical ? 'v-' : ''}advice-container`} >
        <div className="main-advice" >
          <div className="header-appointment" >
            <FlagTitle text="我要建言" />
          </div >
          <div className="form-content-wrap">
            <Form layout={'horizontal'} className="advice-form" >
              <FormItem label="标题" >
                {getFieldDecorator('title', {
                  initialValue: initialValue ? initialValue.title : '',
                  rules: [
                    { required: true, message: '请输入标题' }
                  ]
                })(
                  <Input placeholder="请输入标题" />
                )}
              </FormItem >
              <FormItem label="选择留言方式" />
              <RadioGroup className="audio-radio" value={radioValue} onChange={this.onChangeRadio.bind(this)}>
                <Radio className="radio" value >
                  <FormItem label="视频" >
                    <div className="video" id="videoForm" >
                      <img src="images/icon_record_video.png" alt="录制视频" />
                    </div>
                    <Button className="btn-left" onClick={this.onVideoClick.bind(this)} disabled={radioValue === false} >录制</Button >
                  </FormItem >
                </Radio>
                <Radio className="radio" value={false} >
                  <FormItem label="音频" >
                    <div className="audio" id="audioForm">
                      <audio controls="controls" className="audio-content">
                        <source src={audioSrc} type="audio/mp3" />
                      </audio>
                    </div>
                    <Button
                      className="btn-left"
                      onClick={this.onAudioClick.bind(this)}
                      disabled={radioValue === true}
                    >
                      录制
                    </Button >
                  </FormItem >
                </Radio>
              </RadioGroup>
              <FormItem label="内容" >

                {getFieldDecorator('content', {
                  initialValue: initialValue ? initialValue.content : '',
                  rules: [
                    { required: true, message: '请输入内容' }
                  ]
                })(
                  <TextArea placeholder="请输入内容" rows={4} className="textarea" />
                )}
              </FormItem >
              <FormItem label="建言者姓名" >
                {getFieldDecorator('suggester', {
                  initialValue: initialValue ? initialValue.suggester : '',
                  rules: [
                    { required: true, message: '请输入姓名' }
                  ]
                })(
                  <Input placeholder="请输入建言者姓名" style={{ verticalAlign: 'top' }} />
                )}
                <div className="reporter-anonymous">
                  <Checkbox checked={this.state.anonymous} onChange={this.changeAnonymous}><span className="anonymous-text">匿名</span></Checkbox>
                </div>
              </FormItem >
              <FormItem label="身份证号" >
                {getFieldDecorator('id_no', {
                  initialValue: initialValue ? initialValue.id_no : '',
                  rules: [
                    { required: true, message: '请输入身份证号' }
                  ]
                })(
                  <Input placeholder="请输入身份证号" />
                )}
              </FormItem >
              <FormItem label="联系电话" >
                {getFieldDecorator('phone', {
                  initialValue: initialValue ? initialValue.phone : '',
                  rules: [
                    { required: true, message: '请输入联系电话' }
                  ]
                })(
                  <Input placeholder="请输入联系电话" />
                )}
                <Button className="code" onClick={this.sendCaptcha} >
                  {remainingSecond === 60 || remainingSecond === 0
                    ? '获取验证码'
                    : <span>剩余{remainingSecond}s</span>
                  }
                </Button >
              </FormItem >
              <FormItem label="验证码" >
                {getFieldDecorator('code', {
                  initialValue: initialValue ? initialValue.code : '',
                  rules: [
                    { required: true, message: '请输入验证码' }
                  ]
                })(
                  <Input placeholder="请输入验证码" />
                )}
              </FormItem >
              <Button
                className="submit"
                onClick={this.handSubmit.bind(this)}
                loading={this.state.loading}
              >提交</Button >
              <div className="policeman">
                <div className="private" >投诉人可放心填写，为保护投诉人隐私，个人信息不会被公开</div >
                <img src="images/pic_policeman.png" alt="" className="police-pic" />
              </div >
            </Form >
          </div>
          <OnVideoModal
            ref={(ref) => {
              this.OnVideoModal = ref;
            }}
            onOk={this.OnVideoEditOk.bind(this)}
          />
          <OnAudioModal
            ref={(ref) => {
              this.OnAudioModal = ref;
            }}
            onOk={this.OnAudioEditOk.bind(this)}
          />
        </div >
        <SubmitModal
          ref={(ref) => {
            this.submitModal = ref;
          }}
          onReturn={this.handCliCk}
        />
      </div >
    );
  }
}


function mapStateToProps(state) {
  return {
    ...state.route,
    ...state.webReducer
  };
}

export default Form.create()(connect(mapStateToProps)(AdviceDetails));

